<?php
class Demo {
	public static function test_altf($item2, $key) {
		echo "altf $key .$item2 <br />\n";
	}
}
class Hungdv7DemoArrayFunctionsController extends AppController {
	public function testArrayWalk() {
		$fruits = array (
				"d" => "lemon",
				"a" => "orange",
				"b" => "banana",
				"c" => "apple" 
		);
		function test_alter(&$item1, $key, $prefix) {
			$item1 = "$prefix: $item1";
		}
		function test_print($item2, $key) {
			echo "$key. $item2<br />\n";
		}
		
		echo "Before ...:<br/>";
		array_walk ( $fruits, 'Demo::test_altf' );
		
		array_walk ( $fruits, 'test_alter', 'fruit' );
		echo "... and after:<br/>";
		
		array_walk ( $fruits, 'test_print' );
		
		exit ();
	}
	public function testArrayWalk1() {
		function enumerate(&$item1, $key, &$startNum) {
			$item1 = $startNum ++ . " $item1";
		}
		
		$num = 1;
		
		$fruits = array (
				"lemon",
				"orange",
				"banana",
				"apple" 
		);
		array_walk ( $fruits, 'enumerate', $num );
		
		echo '<pre>';
		print_r ( $fruits );
		echo '</pre>';
		
		echo '$num is: ' . $num . "\n";
		exit ();
	}
	private function generateArray($size) {
		$a = array ();
		for($i = 0; $i < $size; $i ++) {
			array_push ( $a, rand ( 1, $size ) );
		}
		return $a;
	}
	public function benchmarkArrayWalk() {
		// generate large array
		$a = $this->generateArray ( 13000 );
		
		// $$$ benchmark array_wak
		$start = microtime ( true );
		function createIndex(&$item, $key, $start) {
			$item = $start ++ . " / $item";
		}
		$num = 1;
		array_walk ( $a, 'createIndex', $num );
		echo '<br/>array walk ';
		print_r ( microtime ( true ) - $start );
		
		// $$$ benchmark for each
		$start = microtime ( true );
		$num = 1;
		foreach ( $a as $key => $value ) {
			$a [$key] = $num ++ . " / $value";
			if($key % 2 == 0){
				
			}
		}
		echo '<br/> for each ';
		print_r ( microtime ( true ) - $start );
		
		// $$$benchmark array_map
		$start = microtime ( true );
		$b = array_map ( function ($val) {			
			/* if($val == 10){
				echo 'break at val = 10';
				return;
			} */
				
			return " $val";
		}, $a );
		
		echo '<br/> array_map ';
		print_r ( microtime ( true ) - $start );
		
		/*
		 * echo '<pre>'; print_r($b); echo '</pre>';
		 */
		exit ();
	}
	public function benchmarkArrayWalk2() {
		$start = microtime ( true );
		
		$a = $this->generateArray ( 13000 );
		function createIndex(&$item, $key, $start) {
			$item = $start ++ . " / $item";
		}
		
		$num = 1;
		array_walk ( $a, 'createIndex', $num );
		
		print_r ( microtime ( true ) - $start );
		
		/*
		 * echo '<pre>'; print_r($a); echo '</pre>';
		 */
		
		exit ();
	}
}